package com.myself.community.service.impl;

import com.myself.community.dao.LoginTicketMapper;
import com.myself.community.dao.UserMapper;
import com.myself.community.entity.LoginTicket;
import com.myself.community.entity.User;
import com.myself.community.service.UserService;
import com.myself.community.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MailClient mailClient;//邮件客户端

    @Autowired
    private TemplateEngine templateEngine;//模板引擎

    /*@Autowired
    private LoginTicketMapper loginTicketMapper;*/

    @Autowired
    private HostHolder hostHolder;

    @Value("${community.path.domain}")
    private String domain;//域名

    @Value("${server.servlet.context-path}")
    private String contextPath;//项目名

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @Override
    public User findUserById(int id) {
        //return userMapper.selectById(id);
        User user = getCache(id);
        if(user==null)
            user=initCache(id);
        return user;
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();

        // 空值处理
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }
        //用户名为空
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空!");
            return map;
        }

        // 验证账号是否已存在
        User u = userMapper.selectByName(user.getUsername());
        if (u != null) {
            map.put("usernameMsg", "该账号已存在!");
            return map;
        }

        // 验证邮箱是否已注册
        u = userMapper.selectByEmail(user.getEmail());
        if (u != null) {
            map.put("emailMsg", "该邮箱已被注册!");
            return map;
        }

        // 注册用户：对象内存入信息
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));//获取盐
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));//盐拼接到MD5加密的字符串后
        user.setType(0);//设置用户类型为0：普通用户
        user.setStatus(0);//账户状态设置未激活
        user.setActivationCode(CommunityUtil.generateUUID());//生成激活码
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));//设置头像
        user.setCreateTime(new Date());//创建时间
        userMapper.insertUser(user);//存入数据库

        /*使用邮件激活账户*/
        //获取Thymeleaf模版
        Context context = new Context();

        //构建接收邮件参数
        context.setVariable("email", user.getEmail());

        //拼接URL激活链接
        // http://localhost:80/community/activation/101/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();

        //构建链接参数
        context.setVariable("url", url);

        //将模版内容转为字符串类型并将参数传入
        String content = templateEngine.process("/mail/activation", context);

        //发送激活邮件
        mailClient.sendMail(user.getEmail(), "激活账号", content);

        return map;

    }

    /**
     * 激活用户账号
     * @param userId
     * @param code
     * @return
     */
    @Override
    public int active(int userId, String code) {
        //获取用户信息
        User user = userMapper.selectById(userId);
        //判断是否以激活
        if(user.getStatus()==1)
            return Code.ACTIVATION_REPEAT;
        //若传入的激活码正确
        else if(user.getActivationCode().equals(code)){
            //更改用户状态为1：表示以激活
            userMapper.updateStatus(userId,1);

            //清除用户缓存
            clearCache(userId);

            //响应激活成功
            return Code.ACTIVATION_SUCCESS;
        }
        //激活码错误
        else
            return Code.ACTIVATION_FAILURE;

    }

    /**
     * 用户登录并且生成登录凭证
     * @param username
     * @param password
     * @param expiredSeconds
     * @return
     */
    @Override
    public Map<String, Object> login(String username, String password, int expiredSeconds) {
        Map<String, Object> map = new HashMap<>();

        // 空值处理
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }

        // 验证账号
        //查询账户是否存在
        User user = userMapper.selectByName(username);
        if (user == null) {
            map.put("usernameMsg", "该账号不存在!");
            return map;
        }

        // 验证账户是否是激活状态
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活!");
            return map;
        }

        // 验证密码
        //获取输入密码+用户对应盐生成的MD5密码串
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确!");
            return map;
        }

        // 生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + (long)expiredSeconds * 1000));

        //存储登录凭证信息
        //loginTicketMapper.insertLoginTicket(loginTicket);
        //登录凭证信息存入Redis
        String key= RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(key,loginTicket,expiredSeconds, TimeUnit.SECONDS);

        //将凭证字符串存入map
        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    /**
     * 用户退出登录
     * @param ticket
     */
    @Override
    public void logout(String ticket) {
        //将登录凭证状态改为1：无效
        //loginTicketMapper.updateStatus(ticket,1);

        //将Redis登录凭证状态改为1：无效
        String key= RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(key);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(key,loginTicket);
    }

    /**
     * 根据凭证号，查询用户登录凭证信息
     * @param ticket
     * @return
     */
    @Override
    public LoginTicket findLoginTicket(String ticket) {
        //return loginTicketMapper.selectByTicket(ticket);
        //从Redis中取当前用户登录凭证信息
        String key= RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(key);
    }

    /**
     * 更新用户头像
     * @param userId
     * @param headerUrl
     * @return
     */
    @Override
    public int updateHeader(int userId, String headerUrl){
        //return userMapper.updateHeader(userId, headerUrl);
        int rows = userMapper.updateHeader(userId, headerUrl);
        //清理用户数据缓存
        clearCache(userId);
        return rows;
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @Override
    public Map<String, Object> updatePassword(String oldPassword, String newPassword) {
        Map<String, Object> map = new HashMap<>();
        //空值判断
        if(StringUtils.isBlank(oldPassword)){
            map.put("oldPasswordMsg","原密码不能为空！");
            return map;
        }
        if(StringUtils.isBlank(newPassword)){
            map.put("newPasswordMsg","新密码不能为空！");
            return map;
        }

        //1.判断用户原密码是否正确
        User user = hostHolder.getUser();
        oldPassword = CommunityUtil.md5(oldPassword + user.getSalt());
        if(!user.getPassword().equals(oldPassword)){
            map.put("oldPasswordMsg","密码输入有误!");
            return map;
        }

        //2.更新密码
        userMapper.updatePassword(user.getId(),CommunityUtil.md5(newPassword+user.getSalt()));

        return map;
    }

    /**
     * 忘记密码，重置密码
     * @param email
     * @param password
     * @return
     */
    @Override
    public Map<String, Object> forgetPassword(String email, String password) {
        HashMap<String, Object> map = new HashMap<>();
        //空值判断
        if(StringUtils.isBlank(email))
            map.put("emailMsg","邮箱不能为空");
        if(StringUtils.isBlank(password))
            map.put("passwordMsg","密码不能为空");
        //邮箱存在性判断
        User user = userMapper.selectByEmail(email);
        if(user==null)
            map.put("emailMsg","邮箱未注册");
        else {
            //密码更新
            userMapper.updatePassword(user.getId(),CommunityUtil.md5(password+user.getSalt()));
        }
        return map;
    }

    /**
     * 根据用户姓名查询用户信息
     * @param username
     * @return
     */
    @Override
    public User findUserByName(String username) {
        return userMapper.selectByName(username);
    }

    /**
     * 1.优先从缓存中取值
     * @param userId
     * @return
     */
    private User getCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 2.取不到时初始化缓存数据
     * @param userId
     * @return
     */
    private User initCache(int userId) {
        //从数据库中获取用户数据保存到Redis
        User user = userMapper.selectById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    /**
     * 3.用户数据变更时清除缓存数据
     * @param userId
     */
    private void clearCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }
}
